package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.mapper.RoleMapper;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper mapper;
    @Override
    public void saveOrUpdate(Role role,Long[] ids) {
        if (role.getId() == null){
            mapper.insert(role);
        }else {
            mapper.deleteRelation(role.getId());
            mapper.updateByPrimaryKey(role);
        }
        if (ids != null) {
            for (Long id : ids) {
            mapper.saveRelation(role.getId(),id);
            }
        }
    }

    @Override
    public void delete(Long id) {
        mapper.deleteRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Role get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public PageResult query(QueryObject qo) {
        int rows = mapper.getCount();
        if (rows == 0){
            return  new PageResult(qo.getPageSize());
        }
        List<Role> list = mapper.selectAll(qo);
        return new PageResult(qo.getCurrentPage(),qo.getPageSize(),rows,list);
    }

    @Override
    public List<Role> getAll() {
        return mapper.getAll();
    }
}
